const express = require('express');
const mysql = require('mysql');
const bodyParser = require('body-parser');
const cors = require('cors'); // 引入cors中间件
const nodemailer = require('nodemailer');
require('dotenv').config();

const app = express();
const port = 8080; // 更新为8080端口

// 创建MySQL连接
const connection = mysql.createConnection({
    host: 'localhost',
    user: 'root', // 替换为你的MySQL用户名
    password: '050601', // 替换为你的MySQL密码
    database: 'musicplayer' // 替换为你的数据库名
});

// 创建邮件传输器
const transporter = nodemailer.createTransport({
    service: 'gmail', // 使用Gmail服务
    auth: {
        user: process.env.GMAIL_USER,
        pass: process.env.GMAIL_PASSWORD
    }
});

// 连接到MySQL数据库
connection.connect((err) => {
    if (err) {
        console.log('没有连接到数据库');
        throw err;
    }
    console.log('Connected to MySQL database');
});

// 使用body-parser中间件解析请求体
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

// 允许跨域请求
app.use(cors());

// 注册接口
app.post('/register', (req, res) => {
    console.log('Received registration request:', req.body);
    const { username, email, password } = req.body;

    // 检查用户名和邮箱是否已存在
    const checkQuery = 'SELECT * FROM users WHERE username = ? OR email = ?';
    connection.query(checkQuery, [username, email], (err, results) => {
        if (err) {
            console.error('Database query error:', err);
            return res.status(500).json({ error: '服务器错误' });
        }

        if (results.length > 0) {
            console.log('Username or email already exists');
            return res.status(400).json({ error: '用户名或邮箱已存在' });
        }

        // 插入新用户
        const insertQuery = 'INSERT INTO users (username, email, password) VALUES (?, ?, ?)';
        connection.query(insertQuery, [username, email, password], (err) => {
            if (err) {
                console.error('Database insert error:', err);
                return res.status(500).json({ error: '注册失败' });
            }
            
            // 发送确认邮件
            const mailOptions = {
                from: process.env.GMAIL_USER,
                to: email,
                subject: '欢迎注册音乐播放器',
                text: `亲爱的 ${username}，\n\n感谢您注册我们的音乐播放器！\n\n您的账号已成功创建。\n\n祝您使用愉快！\n\n音乐播放器团队`
            };

            transporter.sendMail(mailOptions, (error, info) => {
                if (error) {
                    console.error('Email sending error:', error);
                } else {
                    console.log('Email sent:', info.response);
                }
            });

            console.log('User registered successfully');
            res.status(200).json({ message: '注册成功' });
        });
    });
});

// 登录接口
app.post('/login', (req, res) => {
    const { username, password } = req.body;
    console.log('检查用户名和密码是否匹配');
    // 检查用户名和密码是否匹配
    const checkQuery = 'SELECT * FROM users WHERE username = ? AND password = ?';
    connection.query(checkQuery, [username, password], (err, results) => {
        if (err) {
            console.error('Database query error:', err);
            return res.status(500).json({ error: '服务器错误' });
        }

        if (results.length > 0) {
            console.log('注册成功');
            res.status(200).json({ message: '登录成功' });
        } else {
            res.status(400).json({ error: '没有用户信息请注册' });
        }
    });
});

app.listen(port, () => {
    console.log(`Server is running on http://localhost:${port}`);
});